import React, { Component } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Form, Input, Button, Icon, Row, Col, Alert } from 'antd';
import styles from './Login.less';
import { generateAuthPassword } from '../../utils/request';
import { checkBrowser, getBroswer } from '../../utils/utils';

const FormItem = Form.Item;

@connect(state => ({
  login: state.login,
}))
@Form.create()
export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      getForgotPsw: false,
      getTelCode: false,
      type: 'account',
    };
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.login.status === 'ok') {
      router.push('/');
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  onSwitch = (key) => {
    this.setState({
      type: key,
    });
  }

  onGetCaptcha = () => {
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll(['mobile_tel'], (err, values) => {
      if (!err) {
        let count = 59;
        this.setState({ count, getTelCode: true });
        this.interval = setInterval(() => {
          count -= 1;
          this.setState({ count });
          if (count === 0) {
            clearInterval(this.interval);
          }
        }, 1000);
        this.props.dispatch({
          type: 'login/verification_code',
          payload: {
            mobile_tel: values.mobile_tel,
            authcheck_type: 2,
          },
        });
      }
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const { type } = this.state;
    this.props.form.validateFields({ force: true },
      (err, values) => {
        if (!err) {
          this.props.dispatch({
            type: `login/${type}Submit`,
            payload: {
              ...values,
              password: generateAuthPassword(values.password),
            },
          });
        }
      }
    );
  }

  handlePwsSubmit= (e) => {
    e.preventDefault();
    this.props.form.validateFields({ force: true },
      (err, values) => {
        if (!err) {
          this.props.dispatch({
            type: 'login/retrieve_psw',
            payload: {
              ...values,
              authcheck_id: this.props.login.authcheck_id,
              new_password: generateAuthPassword(values.new_password),
              new_password_confirm: null,
            },
          }).then(() => {
            this.setState({
              getForgotPsw: false,
            });
          });
        }
      }
    );
  }

  handleConfirmPassword = (rule, value, callback) => {
    const { getFieldValue } = this.props.form;
    if (value && value !== getFieldValue('new_password')) {
      callback('两次密码输入不一致！');
    }

    // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
    callback();
  }

  handleForgerPsw = () => {
    this.setState({
      getForgotPsw: !this.state.getForgotPsw,
      getTelCode: false,
      code: false,
    });
  }

  renderMessage = (message) => {
    return (
      <Alert
        style={{ marginBottom: 24 }}
        message={message}
        type="error"
        showIcon
      />
    );
  }



  render() {
    const { form, login } = this.props;
    const { getFieldDecorator } = form;
    const { getTelCode, getForgotPsw, count, type } = this.state;
    const sys = getBroswer();

    return (
      <div className={styles.main}>
        {
          !checkBrowser() &&
          <Row gutter={24}>
            <Col span={24}  style={{textAlign:'center'}}>
              <div style={{color:'#ffdc8b'}}>请升级您的浏览器版本</div>
              <div>{`（您当前的浏览器版本是：${sys.broswer.toUpperCase()} ${sys.version.toUpperCase()}）`}</div>
            </Col>
            <Col span={8} style={{padding:0,margin:'30px 0',textAlign:'center'}}>
              <Icon type="chrome" style={{fontSize:60,marginBottom:20}}/>
              <div style={{fontSize:12}}>Chorme(推荐使用)</div>
              <div style={{fontSize:12,color:'rgba(255,255,255,.6)'}}>版本请高于60.00</div>
            </Col>

            <Col span={8} style={{padding:0,margin:'30px 0',textAlign:'center'}}>
              <Icon type="ie" style={{fontSize:60,marginBottom:20}}/>
              <div style={{fontSize:12}}>IE</div>
              <div style={{fontSize:12,color:'rgba(255,255,255,.6)'}}>版本请高于11</div>
            </Col>

            <Col span={8} style={{padding:0,margin:'30px 0',textAlign:'center'}}>
              <Icon type="windows" style={{fontSize:60,marginBottom:20}}/>
              <div style={{fontSize:12}}>Edge</div>
              <div style={{fontSize:12,color:'rgba(255,255,255,.6)'}}>版本请高于14</div>
            </Col>
          </Row>
        }
        {
          !getForgotPsw && checkBrowser() && (
          <Form onSubmit={this.handleSubmit}>
            {
              login.status === 'error' &&
              login.type === 'account' &&
              login.submitting === false &&
              this.renderMessage('账户或密码错误')
            }
            <FormItem>
              {getFieldDecorator('username', {
                rules: [{
                  required: true, message: '请输入用户名！',
                }, {
                  // pattern: /^1\d{10}$/, message: '手机号格式错误！',
                }],
              })(
                <Input
                  size="large"
                  prefix={<Icon type="user" className={styles.prefixIcon} />}
                  placeholder="请输入用户名"
                />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('password', {
                rules: [{
                  required: true,
                  message: '请输入密码！',
                }],
              })(
                <Input
                  size="large"
                  prefix={<Icon type="lock" className={styles.prefixIcon} />}
                  type="password"
                  placeholder="请输入密码"
                />
              )}
            </FormItem>
            <FormItem className={styles.additional}>
              {/*<a className={styles.forgot} onClick={this.handleForgerPsw}>忘记密码</a>*/}
              <Button size="large" loading={login.submitting} className={styles.submit} type="primary" htmlType="submit">
                登录
              </Button>
            </FormItem>
          </Form>
        )}

        {
          getForgotPsw && checkBrowser() && (
          <Form onSubmit={this.handlePwsSubmit}>
            {
              login.status === 'error' &&
              login.type === 'account' &&
              login.submitting === false &&
              this.renderMessage('账户或密码错误')
            }
            <FormItem>
              {getFieldDecorator('mobile_tel', {
                rules: [{
                  required: true, message: '请输入手机号！',
                }, {
                  pattern: /^1\d{10}$/, message: '手机号格式错误！',
                }],
              })(
                <Input
                  size="large"
                  prefix={<Icon type="mobile" className={styles.prefixIcon} />}
                  placeholder="手机号"
                />
              )}
            </FormItem>
            <FormItem>
              <Row gutter={8}>
                <Col span={16}>
                  {getFieldDecorator('verification_code', {
                    rules: [{
                      required: true, message: '请输入验证码！',
                    }],
                  })(
                    <Input
                      size="large"
                      prefix={<Icon type="mail" className={styles.prefixIcon} />}
                      placeholder="验证码"
                    />
                  )}
                </Col>
                <Col span={8}>
                  <Button
                    disabled={count}
                    className={styles.getCaptcha}
                    size="large"
                    onClick={this.onGetCaptcha}
                  >
                    {count ? `${count} s` : '获取验证码'}
                  </Button>
                </Col>
              </Row>
            </FormItem>

            <FormItem>
              {getFieldDecorator('new_password', {
                rules: [{
                  required: true,
                  min: 8,
                  max: 16,
                  pattern: /^(?![^a-zA-Z]+$)(?!\D+$).{8,15}$/,
                  message: '请输入 8-16位，必须包含数字和字母 的新密码',
                }],
              })(
                <Input size="large" placeholder="8-16位，必须包含数字和字母" type="password" />
              )}
            </FormItem>

            <FormItem>
              {getFieldDecorator('new_password_confirm', {
                rules: [{
                  required: true,
                  min: 8,
                  max: 16,
                  pattern: /^(?![^a-zA-Z]+$)(?!\D+$).{8,15}$/,
                  message: '请输入确认密码',
                }, {
                  validator: this.handleConfirmPassword,
                }],
              })(
                <Input size="large" placeholder="请输入确认密码" type="password" />
              )}
            </FormItem>
            <FormItem className={styles.additional}>
              <a className={styles.forgot} onClick={this.handleForgerPsw}>立即登录</a>
              <Button
                size="large"
                loading={login.submitting}
                className={styles.submit}
                type="primary"
                htmlType="submit"
                disabled={!getTelCode}
              >
                取回密码
              </Button>
            </FormItem>
          </Form>
        )}


        {/* <div className={styles.other}> */}
        {/* 其他登录方式 */}
        {/* /!* 需要加到 Icon 中 *!/ */}
        {/* <span className={styles.iconAlipay} /> */}
        {/* <span className={styles.iconTaobao} /> */}
        {/* <span className={styles.iconWeibo} /> */}
        {/* <Link className={styles.register} to="/user/register">注册账户</Link> */}
        {/* </div> */}
      </div>
    );
  }
}
